from flask import Flask, render_template, url_for, session, redirect, request
from . import register
from .forms import RegisForm
from app.models import User, db


@register.route('/', methods=('GET', 'POST'))
def register():
    form2 = RegisForm()
    print(form2.validate_on_submit())
    print('request.method==', request.method)
    if request.method == 'POST':
        if form2.validate_on_submit():
            username = form2.user.data
            password = form2.pwd.data
            password2 = form2.pwd2.data
            phone = form2.phone.data
            email = form2.email.data
            u = User.query.filter_by(user_name=username).first()
            if u is None:
                if password == password2:
                    u = User(user_name=username, user_password=password, email=email, phone=phone)
                    db.session.add(u)
                    db.session.commit()
                    return redirect(url_for('login.login'))
                else:
                    return '密码错误！<a href="/register">单击此处</a>重新注册！'
            else:
                return '用户名已存在!<a href="/register">单击此处</a>重新注册！'
    return render_template('register.html', form=form2)
